﻿using System;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Persons;

namespace PersonsServer
{
    public sealed class PServer
    {
        private readonly Socket _serverSocket;
        public event EventHandler<PersonMessageEventArgs> PersonsMessageEvent;
        public event EventHandler<EventArgs> StartEvent;

        public PServer() 
        {
            _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        public void Start(IPAddress ip, int port, int maxConnections)
        {
            var ipe = new IPEndPoint(ip, port);
            try
            {
                _serverSocket.Bind(ipe);
                _serverSocket.Listen(maxConnections);
                OnStartEvent(new EventArgs());
                var handler = _serverSocket.Accept();
                var bytesToRead = handler.Available;
                var message = new byte[bytesToRead];
                handler.Receive(message, 0, bytesToRead, SocketFlags.None);
                var ms = new MemoryStream(message);
                var bf = new BinaryFormatter();
                ms.Position = 0;
                var person = (Person)bf.Deserialize(ms);
                OnPersonsMessageEvent(new PersonMessageEventArgs(person));
                ms.Close();
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
            catch (Exception e)
            {
                throw e;
            }

        }

        public void Stop()
        {
            if (_serverSocket != null) _serverSocket.Close();
        }

        private void OnPersonsMessageEvent(PersonMessageEventArgs args)
        {
            var handler = PersonsMessageEvent;
            if (handler != null)
            {
                handler(this, args);
            }
        }

        private void OnStartEvent(EventArgs args)
        {
            var handler = StartEvent;
            if (handler != null)
            {
                handler(this, args);
            }
        }
    }
} 